package gpl.scotlandyard.utils;

import java.io.File;
import java.util.HashMap;

import javax.swing.ImageIcon;

import org.apache.log4j.Logger;

/**
 * Ensures that icons are loaded only ones.
 * <p>
 * @author Norbert Martin
 */
public class ImageProvider {

  private static final Logger _log = Logger.getLogger(ImageProvider.class);
  private static final HashMap<String, ImageIcon> loadedIcons = new HashMap<String, ImageIcon>();

  /**
   * Returns the icon associated to this file.
   * @param f file to load as icon
   * @return icon
   */
  public static ImageIcon get(String f) {
    f.getClass();
    final String fullPath = new File(f).getAbsolutePath();
    ImageIcon icon = loadedIcons.get(fullPath);
    if (icon != null) {
      //_log.debug("Get image : " + fullPath);
      return icon;
    }
    icon = new ImageIcon(fullPath);
    if (icon.getIconWidth() == -1 && icon.getIconHeight() == -1) {
      _log.error("Image can't been loaded : " + fullPath);
    } else {
      _log.info("Image loaded : " + fullPath);
      loadedIcons.put(fullPath, icon);
    }
    return icon;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Loaded : ").append("\r\n");
    for (String key : loadedIcons.keySet()) {
      ImageIcon img = loadedIcons.get(key);
      sb.append(key).append(" : ").append(img.getIconWidth());
      sb.append("x").append(img.getIconHeight());
    }
    return sb.toString();
  }
}
